package com.supor.aiot.mine.ui.wish;

import android.content.Intent;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.entity.DictionaryBean;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.RefreshHelper;
import com.supor.aiot.common.interfaces.OnByItemFilterClickListener;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.bean.Dictionary;
import com.supor.aiot.mine.bean.WishBean;
import com.supor.aiot.mine.databinding.ActivityWishBinding;
import com.supor.aiot.mine.ui.adapter.WishAdapter;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2021, by het, ShenZhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: WishActivity <br>
 * 作者: lei <br>
 * 日期: 2021/8/31 <br>
 */
@Route(path = PathUrl.PATH_ADD_IPS)
public class WishActivity extends BaseMVVMActivity<WishViewModel, ActivityWishBinding> {

    private WishAdapter wishAdapter;
    private AppBasicDialog deleteDialog;
    private int operationPosition = -1;
    View footer;
    List<Dictionary> dictionaryList = new ArrayList<>();

    @Override
    protected int resourceId() {
        return R.layout.activity_wish;
    }

    @Override
    protected void initView() {
        super.initView();
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        initRecyclerView();
    }

    private void initRecyclerView() {

        // BindDevice布局管理器
        RefreshHelper.initLinear(bindingView.rcvWish,
                getResources().getDimensionPixelSize(R.dimen.dp_0));
        bindingView.rcvWish.setRefreshEnabled(true);
        bindingView.rcvWish.setOnRefreshListener(this::refresh);
        bindingView.rcvWish.setLoadMoreEnabled(true);
        bindingView.rcvWish.setOnLoadMoreListener(() -> {
            if (viewModel != null) {
                viewModel.getWishList(true);
            }
        }, 1000);
        wishAdapter = new WishAdapter(new ArrayList<>());
        bindingView.rcvWish.setOnItemClickListener(new OnByItemFilterClickListener() {
            @Override
            protected void onSingleClick(@NonNull BaseQuickAdapter<?, ?> adapter, View v,
                                         int position) {
                Logc.e("onItemClick: position: " + position);
                // List<IotDevice> list1 = bindDeviceAdapter.getData();
                // IotDevice device = list1.get(position);
                // if (device.classify == 2) {
                //     ToastUtils.getInstance().showCustomToast("暂不支持添加该设备");
                //     startActivity(new Intent(activity, ScanGuideActivity.class));
                //     return;
                // }
            }
        });
        bindingView.rcvWish.setOnItemLongClickListener((v, position) -> {
            showDeleteDialog(position);
            return false;
        });
        bindingView.rcvWish.setAdapter(wishAdapter);
        footer = LayoutInflater.from(this).inflate(R.layout.footer_wish,
                (ViewGroup) bindingView.rcvWish.getParent(), false);
        footer.findViewById(R.id.ll_add_wish).setOnClickListener(v -> {
            Logc.i("footer: click ");
            Intent intent = new Intent(WishActivity.this, AddWishActivity.class);
            intent.putParcelableArrayListExtra(Constants.Key.TASTE_LIST, (ArrayList<? extends Parcelable>) dictionaryList);
            startActivityForResult(intent, Constants.REQUEST_CODE);
        });
        bindingView.rcvWish.addFooterView(footer);

        bindingView.llEmptyAddWish.setOnClickListener(v -> {
            Logc.i("empty: click ");
            Intent intent = new Intent(WishActivity.this, AddWishActivity.class);
            intent.putParcelableArrayListExtra(Constants.Key.TASTE_LIST, (ArrayList<? extends Parcelable>) dictionaryList);
            startActivityForResult(intent, Constants.REQUEST_CODE);
        });
    }

    @Override
    protected void initData() {
        super.initData();
        viewModel.getWishListData().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Error) {
                String error = ((Result.Error) result).getErrorMsg();
                Logc.e("onChanged: add ips failed: " + error);
                ToastUtils.getInstance().showCustomToast(error);
                checkEmpty();
            } else if (result instanceof Result.Success) {
                Logc.e("onChanged: get ips success: " + bindingView.rcvWish.isRefreshing());
                List<WishBean> list = (List<WishBean>) result.getData();
                if (bindingView.rcvWish.isRefreshing()) {
                    wishAdapter.setNewData(list);
                } else {
                    wishAdapter.addData(list);
                    bindingView.rcvWish.setRefreshing(false);
                }
                checkEmpty();
            }
        });
        viewModel.getDeleteResult().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast(((Result.Error) result).getErrorMsg());
            } else if (result instanceof Result.Success) {
                int pos = (int) result.getData();
                wishAdapter.removeData(pos);
                if (pos == 0) {
                    wishAdapter.notifyDataSetChanged();
                }
                checkEmpty();
            }
        });
        viewModel.getTasteData().observe(this, result -> {
            if (result instanceof Result.Success) {
                List<DictionaryBean> list = (List<DictionaryBean>) result.getData();
                for (DictionaryBean s : list) {
                    Dictionary dictionary = new Dictionary();
                    dictionary.dictionaryBean = s;
                    dictionaryList.add(dictionary);
                }
                wishAdapter.setDictionaryList(dictionaryList);
                viewModel.getWishList(false);
            } else if (result instanceof Result.Error) {
            }
        });

        viewModel.getTaste();
        viewModel.getLoadMoreData().observe(this, s -> bindingView.rcvWish.loadMoreEnd());
    }

    private void checkEmpty() {
        if (wishAdapter.getData().size() == 0) {
            bindingView.rlWish.setVisibility(View.GONE);
            bindingView.rlEmpty.setVisibility(View.VISIBLE);
            bindingView.rcvWish.removeFooterView(footer);
            return;
        }
        bindingView.rlWish.setVisibility(View.VISIBLE);
        bindingView.rlEmpty.setVisibility(View.GONE);
    }

    private void showDeleteDialog(int position) {
        if (deleteDialog != null) {
            if (deleteDialog.isShowing()) {
                return;
            } else {
                deleteDialog.show();
            }
            return;
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(this, false);
        builder.setTitle(R.string.delete_wish);
        builder.setMessage(R.string.delete_wish_msg);
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            List<WishBean> list = wishAdapter.getData();
            operationPosition = position;
            WishBean device = list.get(position);
            showLoading();
            viewModel.deleteWish(device.wishId, operationPosition);
            dialog.cancel();
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        deleteDialog = builder.create();
        deleteDialog.setCancelable(false);
        deleteDialog.show();
    }

    protected void refresh() {
        if (viewModel != null) {
            bindingView.rcvWish.loadMoreComplete();
            viewModel.getWishList(false);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_CODE) {
            if (resultCode == 1) {
                bindingView.rcvWish.setRefreshing(true);
            }
        }
    }
}
